import { _decorator, AnimationClip, Component, Node,Animation, SpriteFrame } from 'cc';
import { FSM_PARAMS_TYPE_ENUM } from '../Enums';
import State from './State';
import { SubStateMachine } from './SubStateMachine';

const { ccclass, property } = _decorator;

type ParamsValueType=boolean|number

// 参数接口
export interface IParamsValue{
  type:FSM_PARAMS_TYPE_ENUM,
  value:ParamsValueType
}

export const getInitParamsTrigger=()=>{
  return {
    type:FSM_PARAMS_TYPE_ENUM.TRIGGER,
    value:false
  }
}

export const getInitParamsNumber=()=>{
  return {
    type:FSM_PARAMS_TYPE_ENUM.NUMBER,
    value:0
  }
}

@ccclass('StateMachine')
export abstract class StateMachine extends Component {

  // 核心属性
  private _currentState: State|SubStateMachine = null               // 当前状态
  params: Map<string, IParamsValue> = new Map()     // 参数列表
  stateMachines: Map<string, State|SubStateMachine> = new Map()     // 状态机列表
  animationComponent: Animation                     // 动画组件
  waitingList: Array<Promise<SpriteFrame[]>> = []   // 资源加载等待列表

  getParams(paramsName:string){
    if(this.params.has(paramsName)){
      return this.params.get(paramsName).value
    }
  }

  // 设置参数并触发状态检查
  setParams(paramsName: string, value: ParamsValueType) {
    if (this.params.has(paramsName)) {
      this.params.get(paramsName).value = value
      this.run()  // 触发状态转换检查
      this.resetTrigger() // 重置触发器
    }
  }

  get currentState(){
    return this._currentState
  }

  set currentState(newState:State|SubStateMachine){
    this._currentState=newState
    this._currentState.run()
  }

  resetTrigger(){
    for(const [_,value] of this.params)
      if(value.type===FSM_PARAMS_TYPE_ENUM.TRIGGER){
        value.value=false
      }
  }

  abstract init():void
  abstract run():void
}


